package org.newcih.dao.impl;

import org.newcih.dao.IBaseDao;

import java.lang.reflect.Type;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

//import org.hibernate.SessionFactory;
//import org.springframework.beans.factory.annotation.Autowired;

/**
 * 持久层公共的基础服务的实现类
 */
public class BaseDao<T, PK extends java.io.Serializable> implements IBaseDao<T, PK> {

    //1.泛型反射类
    private Class<T> entityClass;

//	@Autowired
//	protected SessionFactory sessionFactory;

    @PersistenceContext
    protected EntityManager em;


    @SuppressWarnings({"unchecked", "rawtypes"})
    public BaseDao() {
        //sessionFactory = HibernateUtil.getSessionFactory();
        //2.通过反射获取子类确定的泛型类
        Type genType = getClass().getGenericSuperclass();
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        entityClass = (Class) params[0];
    }

    @Override
    public void save(T entity) {
        em.persist(entity);
    }

    @Override
    public void update(T entity) {
        em.merge(entity);
    }

    @Override
    public void delete(T entity) {
        em.remove(entity);
    }

    //HQL:面向对象的HQL
    //1.类对象查询,HQL中 select *可以省略直接from
    @SuppressWarnings("unchecked")
    public List<T> findAll() {
        List<T> lists = null;
        lists = em.createQuery("from " + entityClass.getName()).getResultList();
        return lists;
    }


    @Override
    public T findById(PK id) {
        return em.find(entityClass, id);
    }
}
